<template>
  <el-card class="my-bookings-container">
    <h2>我的预约</h2>

    <NotificationDispatcher />

    <div class="filters">
      <el-select v-model="filterStatus" placeholder="状态筛选" clearable>
        <el-option label="待审核" value="0" />
        <el-option label="已通过" value="1" />
        <el-option label="已拒绝" value="2" />
        <el-option label="已取消" value="3" />
      </el-select>
      <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
      />
      <el-button type="primary" @click="loadBookings">筛选</el-button>
    </div>

    <el-table :data="bookings" style="width: 100%" v-loading="loading">
      <el-table-column prop="room" label="会议室" width="180" />
      <el-table-column prop="date" label="日期" width="120" sortable />
      <el-table-column label="时间段" width="150">
        <template #default="{ row }">
          {{ row.startTime }} - {{ row.endTime }}
        </template>
      </el-table-column>
      <el-table-column prop="purpose" label="用途" />
      <el-table-column label="状态" width="100" sortable>
        <template #default="{ row }">
          <el-tag :type="statusType[row.status]" size="small">
            {{ statusText[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button
              v-if="row.status === 0"
              size="small"
              @click="handleEdit(row)"
          >
            修改
          </el-button>
          <el-button
              v-if="row.status === 0 || row.status === 1"
              size="small"
              type="danger"
              @click="handleCancel(row)"
          >
            {{ row.status === 1 ? '取消' : '撤回' }}
          </el-button>
          <el-button
              v-if="row.status === 1"
              size="small"
              type="warning"
              @click="handleTransfer(row)"
          >
            转让
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
          background
          layout="prev, pager, next"
          :total="totalItems"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 转让对话框 -->
    <el-dialog v-model="transferDialogVisible" title="转让预约" width="500px">
      <el-form v-if="selectedBooking">
        <el-form-item label="当前预约">
          <div>{{ selectedBooking.room }} ({{ selectedBooking.date }} {{ selectedBooking.startTime }}-{{ selectedBooking.endTime }})</div>
        </el-form-item>
        <el-form-item label="转让给">
          <el-select v-model="transferUserId" placeholder="选择成员">
            <el-option
                v-for="user in assignableUsers"
                :key="user.id"
                :label="user.name"
                :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="confirmTransfer">确认转让</el-button>
          <el-button @click="transferDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import {ElMessage, ElMessageBox, ElNotification} from 'element-plus'
import { useUserInfoStore } from '../../stores/userInfo'
import NotificationDispatcher from '../../components/NotificationDispatcher.vue'
import dayjs from 'dayjs'

interface Booking {
  id: number;
  room: string;
  date: string;
  startTime: string;
  endTime: string;
  purpose: string;
  status: number; // 0: 待审核, 1: 已通过, 2: 已拒绝, 3: 已取消
  createTime: string;
}

interface User {
  id: number;
  name: string;
}

const userInfoStore = useUserInfoStore()

// 状态定义
const statusText = ['待审核', '已通过', '已拒绝', '已取消']
const statusType = ['warning', 'success', 'danger', 'info']

// 数据状态
const bookings = ref<Booking[]>([])
const loading = ref(true)
const filterStatus = ref('')
const dateRange = ref([])
const transferDialogVisible = ref(false)
const selectedBooking = ref<Booking | null>(null)
const transferUserId = ref<number | null>(null)

// 分页参数
const totalItems = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

// 可转让的用户
const assignableUsers = ref<User[]>([
  { id: 1001, name: '张三' },
  { id: 1002, name: '李四' },
  { id: 1003, name: '王五' }
])

// 初始化加载数据
onMounted(() => {
  loadBookings()
})

// 加载预约数据
const loadBookings = () => {
  loading.value = true
  setTimeout(() => {
    // 模拟数据
    bookings.value = generateBookings(30)
    totalItems.value = bookings.value.length
    loading.value = false
  }, 800)
}

// 修改后的数据生成方法（仅调整日期部分）
const generateBookings = (count: number): Booking[] => {
  const rooms = Array.from({length: 30}, (_, i) => {
    const buildingIndex = i % 7;
    const building = String.fromCharCode(65 + buildingIndex); // A-G
    const floor = Math.floor(i / 7) + 1;
    const roomNum = 100 + (i % 20);
    return `${building}区${building}${floor}号楼${roomNum}`;
  });

  const purposes = [
    '项目进度会议',
    '产品需求评审',
    '团队周例会',
    '客户需求讨论',
    '技术方案评审',
    '新人培训',
    '跨部门协调会'
  ]
  const now = new Date()

  // 生成不同日期的预约（过去7天到未来30天随机分布）
  return Array.from({ length: count }, (_, i) => {
    // 随机分布在过去7天到未来30天之间
    const dayOffset = Math.floor(Math.random() * 87) - 67 // -7到30
    const date = new Date(now.getTime() + (dayOffset * 24 * 60 * 60 * 1000))

    // 工作时间段（保持不变）
    const startHour = 9 + Math.floor(Math.random() * 7) // 9-15点开始
    const durationOptions = [0.5, 1, 1.5, 2]
    const duration = durationOptions[Math.floor(Math.random() * durationOptions.length)]
    const endHour = startHour + duration

    // 状态分布（保持不变）
    const statusRandom = Math.random()
    const status = statusRandom > 0.7 ? 0 :
        statusRandom > 0.9 ? 2 :
            1

    return {
      id: i + 1000,
      room: rooms[Math.floor(Math.random() * rooms.length)],
      date: dayjs(date).format('YYYY-MM-DD'), // 格式化日期
      startTime: `${startHour}:${Math.random() > 0.5 ? '00' : '30'}`,
      endTime: `${endHour}:${Math.random() > 0.5 ? '00' : '30'}`,
      purpose: purposes[Math.floor(Math.random() * purposes.length)],
      status,
      createTime: dayjs(date).subtract(1, 'day').toISOString() // 创建时间设为前一天
    }
  })
}

// 分页事件处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  // 实际项目中这里会重新加载数据
}

// 修改预约
const handleEdit = (booking: Booking) => {
  ElMessageBox.confirm('确定要修改此预约吗?', '修改预约', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('预约修改成功，等待重新审核')
    // 实际项目中这里会调用API
  })
}

// 取消预约
const handleCancel = (booking: Booking) => {
  const action = booking.status === 1 ? '取消' : '撤回'

  ElMessageBox.confirm(`确定要${action}此预约吗?`, `${action}预约`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    booking.status = 3 // 已取消
    ElMessage.success(`预约已${action}`)
  })
}

// 转让预约
const handleTransfer = (booking: Booking) => {
  selectedBooking.value = booking
  transferUserId.value = null
  transferDialogVisible.value = true
}

// 确认转让
const confirmTransfer = () => {
  if (!transferUserId.value) {
    ElMessage.warning('请选择要转让的成员')
    return
  }

  const userName = assignableUsers.value.find(u => u.id === transferUserId.value)?.name || '未知成员'

  ElMessageBox.confirm(
      `确定将预约转让给 ${userName} 吗?`,
      '确认转让',
      { confirmButtonText: '确定', cancelButtonText: '取消' }
  ).then(() => {
    transferDialogVisible.value = false
    ElMessage.success('转让申请已提交，等待管理员审核')
  })
}

// 假设这是你的预约数据，真实可从接口获取
const upcomingBookings = ref([
  { room: 'VIP会议室', time: '2025-06-30 21:30' },
  { room: '大会议室', time: '2025-07-01 14:00' }
])

onMounted(() => {
  const now = dayjs()
  const today = now.format('2025-06-30')

  // 找出今天的预约
  const todayBookings = upcomingBookings.value.filter(b =>
      b.time.startsWith(today)
  )

  if (todayBookings.length > 0) {
    ElNotification({
      title: '预约提醒',
      message: `您今天有 ${todayBookings.length} 条预约，请准时使用会议室`,
      type: 'info'
    })
  }
})

</script>

<style scoped lang="scss">
.my-bookings-container {
  padding: 20px;

  h2 {
    margin-top: 0;
    margin-bottom: 20px;
    color: #333;
  }

  .filters {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
    flex-wrap: wrap;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>